//
// Created by china on 25-1-7.
//

#include "OfflineMessageModel.h"

//offlinemessage 表的操作

bool OfflineMessageModel::insert(const struct MySQLTable::OfflineMessage&  offlinemessage) {
    LOG_INFO<<"OfflineMessageModel::insert";

    if(offlinemessage.userid == -1){
        LOG_ERROR<<"不是有效用户";
        return false;
    }

    char sql[512];
    std::sprintf(sql, "INSERT INTO offlinemessage(userid,message) values(%d,'%s')", offlinemessage.userid, offlinemessage.message.c_str());

    auto pool = Pool::getInstance();
    auto conn = pool->getFreeConn();
    if(conn->update(sql)){
        return true;
    }
    return false;
}

bool OfflineMessageModel::remove(const struct MySQLTable::User&  user) {
    LOG_INFO<<"OfflineMessageModel::remove";

    if(user.id == -1){
        LOG_INFO<<"不是有效用户";
        return false;
    }

    char sql[512];
    std::sprintf(sql, "DELETE FROM offlinemessage WHERE userid=%d ", user.id);

    auto pool = Pool::getInstance();
    auto conn = pool->getFreeConn();
    if(conn->update(sql)){
        return true;
    }
    return false;
}

std::vector<std::string> OfflineMessageModel::query(const struct MySQLTable::User&  user) {
    LOG_INFO<<"OfflineMessageModel::query";

    if(user.id == -1){
        LOG_INFO<<"不是有效用户";
        return std::vector<std::string>();
    }

    char sql[512];
    std::sprintf(sql, "SELECT message FROM offlinemessage WHERE userid=%d ", user.id);
    std::vector<std::string> msgVector;

    auto pool = Pool::getInstance();
    auto conn = pool->getFreeConn();
    MYSQL_RES *res = conn->query(sql);
    if(res != nullptr){
        MYSQL_ROW row;
        while ((row = mysql_fetch_row(res)) != nullptr){
            msgVector.push_back(row[0]);
        }
    }
    mysql_free_result(res);

    return msgVector;
}
